package org.imdm.portal.loadchecker.ui;

import org.zkoss.zul.Label;
import org.zkoss.zul.ListModel;
import org.zkoss.zul.ListModelMap;
import org.zkoss.zul.Timer;
import org.zkoss.zul.event.ListDataEvent;
import org.zkoss.zul.event.ListDataListener;
//import java.text.DateFormat;
//import java.util.Date;

@SuppressWarnings("serial")
public class SortableLoadModel  extends ListModelMap implements ListDataListener{

	ListModel	_model;
	Label		_refresh_time_label;
	Timer		_refresh_timer;
	int			change_event_counter = 0;

	public SortableLoadModel(ListModel m, Label l, Timer t) {
		_model = m;
		_refresh_time_label = l;
		_refresh_timer = t;
		// copy proxy model data into this model.
		for ( int i = 0; i < _model.getSize(); i++) {
			LoadInfo li = (LoadInfo)_model.getElementAt(i);
			put(li.getServer(), li);
		}
		_model.addListDataListener(this);
	}

	// implements ListDataListener
	public void onChange(ListDataEvent event) {
		// copy changed proxy model data into this model.
		LoadInfo li = (LoadInfo)_model.getElementAt(event.getIndex0());
		put(li.getServer(), li);
		fireEvent(ListDataEvent.CONTENTS_CHANGED, this.indexOf(li), this.indexOf(li));

		if ( change_event_counter == 0 ) _refresh_timer.stop();
		change_event_counter++;
		if ( change_event_counter >= _model.getSize() ) {
			// set the refresh time label
//			DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
//			String now = df.format(new Date());
			_refresh_time_label.setValue("just now ( < 1 minute )");
			_refresh_timer.start();
			change_event_counter = 0;
		}
	}
}
